<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org";>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link type="text/css" rel="stylesheet" th:href="@{/css/select2.css}">
    <link type="text/css" rel="stylesheet" th:href="@{/css/bootstrap.css}">
</head>

<body>
<label class="control-label col-sm-1">可数可选 </label>
<div class="col-sm-3">
    <select class="select_gallery-multiple" multiple="multiple" style="width:100%;" onchange="getSelectData()" id="mul-itdragon">
        <optgroup label="职位" id="selectCate">
        </optgroup>
    </select>
</div>

<script type="text/javascript" th:src="@{/js/jquery-2.1.0.js}"></script>
<script type="text/javascript" th:src="@{/js/select2.js}"></script>
<script type="text/javascript" th:src="@{/js/bootstrap.js}"></script>

<script>
    $(function () {
        $.ajax({
            url:"/getData",
            type : 'post',
            dataType:'json',
            cache:false,
            success:function(data){
                var result = JSON.stringify(data);
                var json = eval('(' + result + ')');
                if(json && json.length >0){
                    var options=[];
                    for(var i =0;i<json.length;i++){
                        options.push("<option value="+json[i].id+">"+json[i].userName+"</option>");
                    }
                    $("#selectCate").append(options);
                }

            }
        });
    });



    // 初始化多选select2
    $(".select_gallery-multiple").select2();

    // 初始化单选select2
    $(".select_gallery").select2();


    // 通过id获取select2的value值
    function getSelect2Value(obj) {
        var select2Obj = $('#'+obj).select2();
        return select2Obj.select2("val");
    }

    // 通过id获取select2的text值，这里的text值可能有空格，需注意
    function getSelect2Text(obj) {
        var select2Obj = $('#'+obj).select2();
        return select2Obj.find("option:selected").text();
    }

    // 通过text 设置select2的默认值
    function select2ByText (obj, text) {
        var select2Obj = $('#'+obj).select2();
        $(obj).select("option").each(function(data){
            if (text == data.text.strip()) {
                select2Obj.val(data.value).trigger("change");
            }
        });
    }

    // 通过value 设置select2的默认值
    function select2ByValue (obj, value) {
        var select2Obj = $('#'+obj).select2();
        select2Obj.val(value).trigger("change");
    }


    function getSelectData(){
        console.log(getSelect2Value("mul-itdragon"));
        console.log(getSelect2Text("itdragon"));
        var mulItdragonVal = $("#mul-itdragon").select2("val");
        if (null == mulItdragonVal) {
            return ;
        }


    }
</script>
</body>

</html>